package jnpf.service.impl;

import jnpf.base.entity.DictionaryDataEntity;
import jnpf.entity.*;
import jnpf.mapper.MzCompilationtypeMapper;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.util.RandomUtil;
import java.math.BigDecimal;
import cn.hutool.core.util.ObjectUtil;
import jnpf.permission.model.authorize.AuthorizeConditionModel;

import jnpf.util.GeneraterSwapUtil;
import jnpf.database.model.superQuery.SuperQueryJsonModel;
import jnpf.database.model.superQuery.ConditionJsonModel;
import jnpf.database.model.superQuery.SuperQueryConditionModel;


import jnpf.permission.service.AuthorizeService;


import java.lang.reflect.Field;
import com.baomidou.mybatisplus.annotation.TableField;
import java.util.stream.Collectors;
import jnpf.model.mzcompilationtype.*;










import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.text.SimpleDateFormat;
import jnpf.util.*;
import java.util.*;
import jnpf.base.model.filter.RuleInfo;
import jnpf.util.GenUtil;
/**
 *
 * mzCompilationtype
 * 版本： V3.2.0
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2024-01-15
 */
@Service
public class MzCompilationtypeServiceImpl extends ServiceImpl<MzCompilationtypeMapper, MzCompilationtypeEntity> implements MzCompilationtypeService{



        @Autowired
        private GeneraterSwapUtil generaterSwapUtil;

        @Autowired
        private UserProvider userProvider;

        @Autowired
        private AuthorizeService authorizeService;


    @Override
    public List<MzCompilationtypeEntity> getTreeList(MzCompilationtypePagination mzCompilationtypePagination) {
        QueryWrapper<MzCompilationtypeEntity> queryWrapper = new QueryWrapper<>();
        if(StringUtil.isNotEmpty(mzCompilationtypePagination.getTypecode())){
            queryWrapper.lambda().and(
                    t -> t.eq(MzCompilationtypeEntity::getTypecode, mzCompilationtypePagination.getTypecode())
            );
        }
        if(StringUtil.isNotEmpty(mzCompilationtypePagination.getTypename())){
            queryWrapper.lambda().and(
                    t -> t.eq(MzCompilationtypeEntity::getTypename, mzCompilationtypePagination.getTypename())
            );
        }
        queryWrapper.lambda().orderByAsc(MzCompilationtypeEntity::getSortCode)
                .orderByDesc(MzCompilationtypeEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public List<MzCompilationtypeEntity> getList(MzCompilationtypePagination mzCompilationtypePagination){
        return getTypeList(mzCompilationtypePagination,mzCompilationtypePagination.getDataType());
    }
    @Override
    public List<MzCompilationtypeEntity> getTypeList(MzCompilationtypePagination mzCompilationtypePagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
		List<List<String>> intersectionList =new ArrayList<>();
		int total=0;
		int mzCompilationtypeNum =0;
        QueryWrapper<MzCompilationtypeEntity> mzCompilationtypeQueryWrapper=new QueryWrapper<>();

//树形，异步父级查询条件
		List<String> allSuperIDlist = new ArrayList<>();
		String superOp ="";
	if (ObjectUtil.isNotEmpty(mzCompilationtypePagination.getSuperQueryJson())){
		SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(mzCompilationtypePagination.getSuperQueryJson(), SuperQueryJsonModel.class);
		String matchLogic = superQueryJsonModel.getMatchLogic();
		List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
		for (ConditionJsonModel conditionjson : superQueryList){
            Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
            Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
            String tableName = configMap.get("relationTable")!=null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
		    if (map.get("multiple") != null) {
		        if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
		            conditionjson.setFieldValue("[]");
		        }
		    }
            conditionjson.setTableName(tableName);
		}
		List<String> allSuperList = new ArrayList<>();
		List<List<String>> intersectionSuperList  = new ArrayList<>();



        int mzCompilationtypeNum1 = 0;
        QueryWrapper<MzCompilationtypeEntity> mzCompilationtypeSuperWrapper = new QueryWrapper<>();
        mzCompilationtypeNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(mzCompilationtypeSuperWrapper,superQueryList,matchLogic,"mz_compilationtype")
        ,new MzCompilationtypeEntity(),mzCompilationtypeNum1);
            if (mzCompilationtypeNum1>0){
            List<String> mzCompilationtypeList =this.list(mzCompilationtypeSuperWrapper).stream().map(MzCompilationtypeEntity::getId).collect(Collectors.toList());
            allSuperList.addAll(mzCompilationtypeList);
            intersectionSuperList.add(mzCompilationtypeList);
            }
		superOp = matchLogic;
		//and or
		if(matchLogic.equalsIgnoreCase("and")){
		    allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
		}else{
		    allSuperIDlist = allSuperList;
		}
    }
    boolean pcPermission = true;
    boolean appPermission = false;
    boolean	isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
    if(isPc && pcPermission){
		if (!userProvider.get().getIsAdministrator()){
			Object mzCompilationtypeObj=authorizeService.getCondition(new AuthorizeConditionModel(mzCompilationtypeQueryWrapper,mzCompilationtypePagination.getMenuId(),"mz_compilationtype"));
            if (ObjectUtil.isEmpty(mzCompilationtypeObj)){
                return new ArrayList<>();
            } else {
                mzCompilationtypeQueryWrapper = (QueryWrapper<MzCompilationtypeEntity>)mzCompilationtypeObj;
                if( mzCompilationtypeQueryWrapper.getExpression().getNormal().size()>0){
                    mzCompilationtypeNum++;
                }
            }
        }
    }
    if(!isPc && appPermission){
		if (!userProvider.get().getIsAdministrator()){
			Object mzCompilationtypeObj=authorizeService.getCondition(new AuthorizeConditionModel(mzCompilationtypeQueryWrapper,mzCompilationtypePagination.getMenuId(),"mz_compilationtype"));
            if (ObjectUtil.isEmpty(mzCompilationtypeObj)){
                return new ArrayList<>();
            } else {
            mzCompilationtypeQueryWrapper = (QueryWrapper<MzCompilationtypeEntity>)mzCompilationtypeObj;
				if( mzCompilationtypeQueryWrapper.getExpression().getNormal().size()>0){
                     mzCompilationtypeNum++;
				}
			}


		}
    }



        if(isPc){
			if(ObjectUtil.isNotEmpty(mzCompilationtypePagination.getTypename())){
            mzCompilationtypeNum++;

                    mzCompilationtypeQueryWrapper.lambda().like(MzCompilationtypeEntity::getTypename,mzCompilationtypePagination.getTypename());

                    }

			if(ObjectUtil.isNotEmpty(mzCompilationtypePagination.getTypecode())){
            mzCompilationtypeNum++;

                    mzCompilationtypeQueryWrapper.lambda().like(MzCompilationtypeEntity::getTypecode,mzCompilationtypePagination.getTypecode());

                    }

        }
		List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
		if (total>0){
		if (intersection.size()==0){
		    intersection.add("jnpfNullList");
		}
         mzCompilationtypeQueryWrapper.lambda().in(MzCompilationtypeEntity::getId, intersection);
		}
        //是否有高级查询
		if (StringUtil.isNotEmpty(superOp)){
		    if (allSuperIDlist.size()==0){
		        allSuperIDlist.add("jnpfNullList");
		    }
		List<String> finalAllSuperIDlist = allSuperIDlist;
            mzCompilationtypeQueryWrapper.lambda().and(t->t.in(MzCompilationtypeEntity::getId, finalAllSuperIDlist));
		}


        //排序
        mzCompilationtypeQueryWrapper.lambda().orderByDesc(MzCompilationtypeEntity::getSortCode);
        /*if(StringUtil.isEmpty(mzCompilationtypePagination.getSidx())){
        mzCompilationtypeQueryWrapper.lambda().orderByDesc(MzCompilationtypeEntity::getSortCode);
        }else{
            try {
            	String sidx = mzCompilationtypePagination.getSidx();
                MzCompilationtypeEntity mzCompilationtypeEntity = new MzCompilationtypeEntity();
				Field declaredField = mzCompilationtypeEntity.getClass().getDeclaredField(sidx);
				declaredField.setAccessible(true);
				String value = declaredField.getAnnotation(TableField.class).value();
                 mzCompilationtypeQueryWrapper="asc".equals(mzCompilationtypePagination.getSort().toLowerCase())?mzCompilationtypeQueryWrapper.orderByAsc(value):mzCompilationtypeQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }*/

        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<MzCompilationtypeEntity> page=new Page<>(mzCompilationtypePagination.getCurrentPage(), mzCompilationtypePagination.getPageSize());
                IPage<MzCompilationtypeEntity> userIPage=this.page(page, mzCompilationtypeQueryWrapper);
                return mzCompilationtypePagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<MzCompilationtypeEntity> list = new ArrayList();
                return mzCompilationtypePagination.setData(list, list.size());
            }
        }else{
            return this.list(mzCompilationtypeQueryWrapper);
        }
    }

    private boolean onlyMainFilter(String moduleId) {
        List<RuleInfo> ruleInfos = generaterSwapUtil.getFilterCondition(moduleId);
        for (RuleInfo info : ruleInfos){
            if(info.getField().contains("_jnpf_") || info.getField().contains("-")){
                return  false;
            }
        }
        return true;
    }

    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type,String tableName) {
        try{
            // 避免空and
            wrapper.apply(" 1=1 ");
            List<RuleInfo> ruleInfos = generaterSwapUtil.getFilterCondition(id);
            for (RuleInfo info : ruleInfos){
                String field=info.getField();
                if ("main".equals(type) && field.contains("-")) {
                    continue;
                }
                if ("main".equals(type) && field.contains("_jnpf_" )) {
                    continue;
                }
                if ("sub".equals(type) && !field.contains("-")) {
                    continue;
                }
                if("sub-jnpf".equals(type) && !field.contains("_jnpf_" )){
                    continue;
                }
                String fieldName = field ;
                String table = "";
                if(field.contains("-")){
                    fieldName= field.split("-")[1];
                    if(!tableName.equals(field.split("-")[0])){
                        continue;
                    }
                }
                if(field.contains("_jnpf_" )){
                    fieldName = field.split("_jnpf_" )[1];
                    table = field.split("_jnpf_" )[0];
                    table = table.replace("jnpf_","");
                }
                if("sub-jnpf".equals(type) && !tableName.equals(table)){
                    continue;
                }
                Field declaredField=aClass.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                String fieldDb=declaredField.getAnnotation(TableField.class).value();
                GenUtil genUtil=JsonUtil.getJsonToBean(info,GenUtil.class);
                genUtil.setDbType("mysql");
                genUtil.solveValue(wrapper, fieldDb);
            }
            return wrapper;
        }catch (Exception e){
            return  wrapper;
        }
    }

    @Override
    public MzCompilationtypeEntity getInfo(String id){
        QueryWrapper<MzCompilationtypeEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(MzCompilationtypeEntity::getId,id);
        return this.getOne(queryWrapper);
    }



    @Override
    public void create(MzCompilationtypeEntity entity){
        this.save(entity);
    }

    @Override
    public boolean update(String id, MzCompilationtypeEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(MzCompilationtypeEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法



    //验证表单唯一字段
    @Override
    public String checkForm(MzCompilationtypeForm form,int i) {
        int total = 0;
		boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
		String id="";
		String countRecover = "";
		if (isUp){
			 id = form.getId();
		}

        return countRecover;
    }


}
